'''
Created on 09.04.2013

@author: doleynik
'''

import cgi
import json
import time
import webapp2

from webapp2_extras.i18n import gettext as _

from apnetmodels.basicmodels import immeuble, general_ledger 
from google.appengine.api import users


from common import functions

from BaseHandler import BaseHandler

class GeneralLedger(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(GeneralLedger, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                        "input_date" : _("Record date"),
                        "source" : _("Source"),
                        "number" : _("Number"),
                        "doc_date" : _("Date"),
                        "ini_subaccount_code" : _("Account code"),
                        "ini_subaccount_name" : _("Account title"),
                        "contr_subaccount_code" : _("Counterparty code"),
                        "contr_subaccount_name" : _("Counterparty title"),
                        "description" : _("Description"),
                        "entry_type" : _("Type of entry"),
                        "debit" : _("Debit"),
                        'credit' : _('Credit'),
                        "period" : _("Period concept"),
                        "reversal" : _("Reversal")
                       }


    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        template_values = {
                           'title': _('General Ledger. %s' % imm.name),
                           'header': _('%s. General Ledger.' % imm.name),
                           'app_user': self.au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'vie',
                           'leftmenu': 'general_ledger',
                           'fields': self.fields
                           }

        template = self.jinja2.get_template('templates/gl_records_list.html')
        self.response.out.write(template.render(template_values))

    def op_list_json(self, *args, **kwargs):        
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        gl = []
        for p in imm.period_concept_set.run():
            for i in p.general_ledger_set.order('lastchange_date').order('ini_subaccount').run():
                debit = None
                if i.debit:
                    debit =  unicode('{:0,.2f}'.format(i.debit))
                credit = None
                if i.credit:
                    credit = unicode('{:0,.2f}'.format(i.credit))
                gl.append([
                           i.lastchange_date.strftime("%d/%m/%y %H:%M:%S"),
                           unicode(i.source),
                           unicode(i.number),
                           i.doc_date.strftime("%d/%m/%y"),
                           unicode(i.ini_subaccount.code),
                           unicode(i.ini_subaccount.name),
                           unicode(i.description),
                           debit,
                           credit,
                           unicode(i.contr_subaccount.code),
                           unicode(i.contr_subaccount.name),
                           unicode(i.period),
                           unicode(i.entry_type),
                           unicode(i.reversal)
                            ])
        ret = {}
        ret['aaData'] = gl
        self.response.out.write(json.dumps(ret))

    def op_delete(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        record_key = kwargs.get('rec_key', "")
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        record = general_ledger.get(record_key)
        if not record:
            self.object_does_not_exist()
            return
        
        ok_message = ''
        alert_message = ''
        
        if self.request.method == 'GET':
            alert_message = _('Are you sure you want to delete record?')
            
        if self.request.method == 'POST':
            rec1 = record
            record.delete()
            while not rec1 is None:
                rec1 = general_ledger.get(record_key)
                time.sleep(1)
            ok_message = _('Record was deleted.')
                
        template_values = {
            'ok_message': ok_message,
            'alert_message': alert_message,
            'fields': self.fields
        }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
